﻿using System.Windows.Forms;
using TechMadeira.Data;

namespace TechMadeira.App.UITypeEditors
{
    public partial class ClientEditorForm : Form
    {
        public ClientEditorForm()
        {
            InitializeComponent();
            InitializeClientsList();
        }

        public IClient SelectedClient
        {
            get
            {
                if ( mClientsListView.SelectedItems.Count == 0 ) return null;
                return mClientsListView.SelectedItems[ 0 ].Tag as IClient;
            }
            set
            {
                foreach ( ListViewItem item in mClientsListView.Items )
                {
                    if ( item.Tag != value ) continue;
                    item.Selected = true;
                    break;
                }
                mClientsListView.Select();
            }
        }

        private void InitializeClientsList()
        {
            foreach ( var client in Repository.Instance.Select<IClient>() )
            {
                AppendClient( client );
            }
        }

        private void AppendClient( IClient aClient )
        {
            var item = new ListViewItem( aClient.NIF, 0 ) { Tag = aClient };
            item.SubItems.Add( aClient.Name );
            mClientsListView.Items.Add( item );

            aClient.OnUpdate += ( subject, data ) => {
                var client = subject as IClient;
                item.Text = client.NIF;
                item.SubItems[1].Text = client.Name;
            };
        }

        private void OnNew( object sender, System.EventArgs e )
        {
            AppendClient( Repository.Instance.CreateObject<IClient>() );
        }

        private void OnSelectedItem( object sender, System.EventArgs e )
        {
            if ( mClientsListView.SelectedItems.Count == 0 ) return;
            mPropertyGrid.SelectedObject = mClientsListView.SelectedItems[ 0 ].Tag;
        }
    }
}
